package com.tmobile.databaseprepare;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.domain.Spine;
import nl.siegmann.epublib.domain.SpineReference;
import nl.siegmann.epublib.domain.TOCReference;
import nl.siegmann.epublib.epub.EpubReader;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;

import com.tmobile.databaseprepare.database.BookDatabase;

public class MainActivity extends Activity {
	String TAG = "MainActivity";
	BookDatabase bookDatabase;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		bookDatabase = BookDatabase.getInstance(getApplicationContext());
//		new CrawlerAsync().execute();
		// new LoadDataAsync().execute();
		 new ReadFileAsync().execute();
	}

	private class ReadFileAsync extends AsyncTask<Void, Void, Void> {
		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(MainActivity.this);
			dialog.setMessage("loading");
			dialog.setCancelable(false);
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			HtmlFileReader fileReader = new HtmlFileReader(
					getApplicationContext());
			fileReader.readAllFile();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (dialog.isShowing())
				dialog.dismiss();
			super.onPostExecute(result);
		}
	}

	private class CrawlerAsync extends AsyncTask<Void, Void, Void> {
		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(MainActivity.this);
			dialog.setMessage("loading");
			dialog.setCancelable(false);
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			Crawler crawler = new Crawler(getApplicationContext());
			for (int i = 0; i < Crawler.CHAPTER_TOTAL; i++) {
				String url = Crawler.BASE_URL
						+ String.valueOf(Crawler.START_CHAPTER_INDEX + i);
				crawler.crawlUrl(url, i);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (dialog.isShowing())
				dialog.dismiss();
			super.onPostExecute(result);
		}
	}

	private class LoadDataAsync extends AsyncTask<Void, Void, Void> {
		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(MainActivity.this);
			dialog.setMessage("loading");
			dialog.setCancelable(false);
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			int storyIndex = 0;
			for (String eachStory : Constants.filePath) {
				readEpubFile(storyIndex, eachStory);
				storyIndex++;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (dialog.isShowing())
				dialog.dismiss();
			super.onPostExecute(result);
		}

	}

	private void readEpubFile(int storyIndex, String filePath) {
		AssetManager assetManager = getAssets();
		try {
			// find InputStream for book
			InputStream epubInputStream = assetManager.open(filePath);
			// Load Book from inputStream
			Book book = (new EpubReader()).readEpub(epubInputStream);
			readTableOfContents(storyIndex, book);
			// readEpubFile(filePath);
		} catch (IOException e) {
			Log.e(TAG, "epublib exception " + e.toString());
		}
	}

	/**
	 * 
	 * @param storyIndex
	 *            thu tu cua truyen
	 * @param book
	 */
	private void readTableOfContents(int storyIndex, Book book) {
		Spine spine = new Spine(book.getTableOfContents());
		int index = 0;
		for (SpineReference bookSection : spine.getSpineReferences()) {
			index++;
			// Log.d(TAG, "index " + index);{
			StringBuffer sb = new StringBuffer();
			Resource res = bookSection.getResource();
			try {
				InputStream is = res.getInputStream();
				BufferedReader r = new BufferedReader(new InputStreamReader(is));
				String line, lineX = "";
				while ((line = r.readLine()) != null) {
					lineX = lineX.concat(Html.fromHtml(line).toString())
							.concat("\n");
					sb.append(line);
					// Log.d(TAG, line);
				}
				Log.i(TAG, "index = " + index);
				// if (index != 2) {
				// ko xu ly spine = 2 : chao mung
				// luu vao bo nho hoac database
				// AppSingleton.getInstance().addToChapterContent(sb.toString());
				com.tmobile.databaseprepare.database.Book bookRecord = new com.tmobile.databaseprepare.database.Book();
				bookRecord.setBookNumber(storyIndex);
				bookRecord.setChapterTitle(getChapterTitle(storyIndex, index));
				bookRecord.setChapterContent(Html.fromHtml(sb.toString())
						.toString());
				bookDatabase.createRecord(bookRecord);
				Log.i(TAG, "insert for chapter " + index + " -----== content: "
						+ Html.fromHtml(sb.toString()).toString());
				// }

			} catch (IOException e) {
			}
		}
	}

	/**
	 * 
	 * @param storyIndex
	 *            tap 1,2,3
	 * @param chapterIndex
	 *            chuong 1,2,3
	 * @return
	 */
	public String getChapterTitle(int storyIndex, int chapterIndex) {
		String chapterOfStory[] = {};
		
		// if (chapterOfStory.length < (chapterIndex-2)){
		// return chapterOfStory[chapterIndex-1];
		// }else
		return "Chương " + String.valueOf(chapterIndex - 1);

	}

	private void readEpubFile(String filePath) {
		AssetManager assetManager = getAssets();
		try {
			// find InputStream for book
			InputStream epubInputStream = assetManager.open(filePath);
			// Load Book from inputStream
			Book book = (new EpubReader()).readEpub(epubInputStream);

			// Log the tale of contents
			logTableOfContents(book.getTableOfContents().getTocReferences(), 0);

		} catch (IOException e) {
			Log.e(TAG, "epublib exception " + e.toString());
		}
	}

	private void logTableOfContents(List<TOCReference> tocReferences, int depth) {

		if (tocReferences == null) {
			return;
		}

		Log.i(TAG, "depth = " + depth);
		for (TOCReference tocReference : tocReferences) {
			StringBuilder tocString = new StringBuilder();
			for (int i = 0; i < depth; i++) {
				tocString.append("\t");
			}
			tocString.append(tocReference.getTitle());
			Log.i(TAG, "here" + tocString.toString());
			// AppSingleton.getInstance()
			// .addToChapterContent(tocString.toString());
			logTableOfContents(tocReference.getChildren(), depth + 1);
		}

	}
}
